package it.cinema.biz;

import it.cinema.CinemaLVisionServlet;
import it.cinema.Response;
import it.cinema.data.ActionData;
import it.cinema.data.Hotspot;
import it.cinema.data.HotspotData;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RequestVisionBiz {

	private static final Logger log = Logger.getLogger(RequestVisionBiz.class.getName());
	private static final float kmDeg = 111.22625f;
	private static String layerName = "cinemavision";
	
	public Response handleRequest(float currLat, float currLon, int radius, int alt, String img) {
		Response response = new Response();

		String film_poster = img;
		// Get all the active hotspots within the specified radius
		List<HotspotData> hotspots = getAll(currLat, currLon, radius, film_poster);

		if (hotspots.size()>0){
			response.setHotspots( createAllHotspots(hotspots, currLat, currLon));
			response.setErrorCode(0);
			response.setErrorString("ok");
			response.setLayer(layerName);
			response.setRefreshDistance(10); // 10 meters
			response.setRefreshInterval(180); // 180 seconds
			response.setImageName(img);
		}else{
			response.setErrorCode(20);
			response.setErrorString("No POI found. Please adjust the range.");
			response.setLayer(layerName);
			response.setRefreshDistance(10); // 10 meters
			response.setRefreshInterval(180); // 180 seconds
		}

		return response;
	}

	public List<HotspotData> getAll(float currLat, float currLon, int radius, String img){

		float delta[] = calculateDelta(radius / 1000, currLat);
		float latmin = currLat - delta[0];
		float latmax = currLat + delta[0];
		float lonmin = currLon - delta[1];
		float lonmax = currLon + delta[1];
		List<HotspotData> hotspots = new ArrayList<HotspotData>();
		List<ActionData> ads = null;

		ResultSet resultSet = null;
        Connection connection = null;
		Statement statement = null;
		HotspotData hsd = null;
		ActionData ad = null;
		
		try {
            connection = CinemaLVisionServlet.getDataSource().getConnection();
            statement = connection.createStatement();
            
            String sourcestring = img;
    		Pattern re = Pattern.compile("_");
    		Matcher m = re.matcher(sourcestring);
    		String img_cleaned = m.replaceAll(" ");

            String query = "SELECT distinct c.nome, c.idcinema, c.lat, c.lon, c.indirizzo, c.citta, c.telefono, c.sito, c.zona FROM dbcinema.cinema c, dbcinema.sala s, dbcinema.sala_proietta_film spf, dbcinema.film f where (c.idcinema = s.cinema_idcinema and s.cinema_idcinema = spf.sala_cinema_idcinema and s.idsala = spf.sala_idsala and spf.film_idfilm = f.idfilm and f.titolo='"+img_cleaned+"');";
            resultSet = statement.executeQuery(query);

            float lat = 0;
            float lon = 0;
            
            while (resultSet.next()) {

            	lat = resultSet.getFloat("lat");
            	lon = resultSet.getFloat("lon");
            	if ( lat >= latmin & lat<= latmax & lon >=lonmin & lon <= lonmax) {
            		hsd = new HotspotData();
            		hsd.setId(resultSet.getString("idcinema"));
            		hsd.setLat(resultSet.getFloat("lat"));
            		hsd.setLon(resultSet.getFloat("lon"));
            		hsd.setTitle(resultSet.getString("nome"));
            		hsd.setLine4(resultSet.getString("citta"));
            		hsd.setLine3(resultSet.getString("indirizzo"));
            		hsd.setLine2(resultSet.getString("zona"));
            		hsd.setImageURL("http://nomami.dlinkddns.com/CinemaLayarServices/content/cinema.jpg");
            		
            		ads = new ArrayList<ActionData>();
            		ad = new ActionData();
            		ad.setLabel("Web Site");
            		ad.setUri(resultSet.getString("sito"));
            		ad.setContentType("text/html");
            		ad.setActivityType(1);
            		ads.add(ad);
            		ad = new ActionData();
            		ad.setLabel("Call Cinema");
            		ad.setUri("tel:"+resultSet.getString("telefono"));
            		ad.setContentType("application/vnd.layar.internal");
            		ad.setActivityType(2);
            		ads.add(ad);
            		ad = new ActionData();
            		ad.setLabel("Trailer");
            		ad.setUri("http://www.mymovies.it/filmclub/2004/06/506/trailer.flv");
            		ad.setContentType("video/flv");
            		ad.setActivityType(3);
            		ads.add(ad);
            		hsd.setActions(ads);
            		
            		hotspots.add(hsd);
            	}
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
        	try {if(null!=resultSet) resultSet.close() ;} catch (SQLException e1){e1.printStackTrace();}
        	try {if(null!=statement) statement.close() ;} catch (SQLException e2){e2.printStackTrace();}
            try {if(null!=connection)connection.close();} catch (SQLException e3){e3.printStackTrace();}
        }		

		return hotspots;
	}
	
	private float[] calculateDelta(int radius, float lat) {
		float[] delta = new float[2];
		delta[0] = radius / kmDeg; // delta Lat
		delta[1] = radius / (float) (kmDeg * Math.cos(Math.toRadians(lat))); // delta Lon
		return delta;
	}

	public List<Hotspot> createAllHotspots(List<HotspotData> hotspots, float currLat, float currLon ) {
		List<Hotspot> results = new ArrayList<Hotspot>();
		for (HotspotData hsd : hotspots) {
			results.add(hsd.createHotSpot(currLat, currLon));
		}
		return results;
	}
}
